//
//  DataCache.m
//  MY QQapp
//
//  Created by liuchengming on 16/11/15.
//  Copyright © 2016年 liuchengming. All rights reserved.
//

#import "DataCache.h"
#import "LoginData.h"

@implementation DataCache
+ (void)loginWithname:(NSString *)name password:(NSString *)password complete:(void (^)(LoginData *))handle
{
    NSDictionary * param = @{
                             @"name":name,
                             @"password":password
                             };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/login.php" dataClass:[param class] complete:^(LoginData *data)
    {
        handle(data);
    }];
}


+ (void)getUesrListAtPage:(int)page complete:(void (^)(LoginData *))handle
{
    NSDictionary * param = @{
                             @"page":@(page)
                             };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/list.php" dataClass:[param class] complete:^(LoginData *data) {
        handle(data);
    }];
}

+ (void)getDataWithParam:(NSDictionary *)param urlString:(NSString *)urlString dataClass:(Class)cls complete:(void (^)(LoginData *data))handle
{
    NSMutableString * str = [[NSMutableString alloc] initWithString:urlString];
    [str appendString:@"?"];
    for (NSString * key in param)
    {
        [str appendFormat:@"%@=%@&",key,param[key]];
    }
    NSString * str1 = [str substringToIndex:str.length - 1];
    
    NSURL * url = [NSURL URLWithString:str1];
    NSURLRequest * req = [NSURLRequest requestWithURL:url];
    NSURLSession * session =[NSURLSession sharedSession];
    
    NSURLSessionDataTask * task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handle([[cls alloc]initWithDictionary:dict]);
        });
    }];
    [task resume];
}

@end
